<template>
  <div class="category">
    <el-button
      type="primary"
      class="mb-10"
      @click="
        dialogVisible = true;
        isAdd = true;
        formData = JSON.parse(JSON.stringify(initFormData));
      "
      >添加商品</el-button
    >
    <el-table :data="tableData" stripe>
      <el-table-column label="序号" width="60">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="_id" label="id" width="200" />
      <el-table-column label="分类图标" prop="covers">
        <template slot-scope="scope">
          <img
            :src="$getImageUrl(scope.row.covers[0])"
            width="120"
            height="75"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="price" label="价格">
        <template slot-scope="scope">
          {{ scope.row.price ? scope.row.price + "元" : "" }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="所属分类">
        <template slot-scope="scope">
          {{ scope.row.cat.name }}
        </template>
      </el-table-column>
      <el-table-column prop="dsc" label="描述" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <div class="operation-wrap">
            <el-button type="primary" @click="editRow(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              confirmButtonText="确定"
              cancelButtonText=""
              icon="el-icon-info"
              iconColor="red"
              :title="`确定删除${scope.row.name}吗？`"
              @onConfirm="deleteRow(scope.row)"
            >
              <el-button type="danger" slot="reference">删除</el-button>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="isAdd ? '添加' : '编辑'"
      :visible.sync="dialogVisible"
      width="45%"
    >
      <el-form ref="form" :model="formData" label-width="120px">
        <el-form-item label="商品名称">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="分类图标">
          <div class="jc-start flex-wrap">
            <el-upload
              v-for="(item, index) in formData.covers"
              :key="index"
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="(file, arg) => handleAvatarSuccess(index, file, arg)"
              :headers="uploadHeaders"
            >
              <img v-if="item" :src="$getImageUrl(item)" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAddAvatarSuccess"
              :headers="uploadHeaders"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input type="number" v-model="formData.price" />
        </el-form-item>
        <el-form-item label="所属分类">
          <el-select v-model="formData.cat" placeholder="请选择">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="formData.dsc" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCommonRow()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCommodity,
  addCommodities,
  editCommodities,
  deleteCommodities
} from "@/api/commodity";
import { getCat } from "@/api/category";
import { Message, MessageBox } from "element-ui";
import { getToken } from "@/utils/auth";
export default {
  name: "",
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      formData: {
        name: "",
        covers: [],
        cat: "",
        dsc: ""
      },
      initFormData: {
        name: "",
        covers: [],
        cat: "",
        dsc: ""
      },
      isAdd: false,
      editRowData: {},
      uploadHeaders: { Authorization: `Bearer ${getToken()}` },
      uploadUrl: process.env.VUE_APP_UPLOAD,
      categories: []
    };
  },
  created() {
    this.getCom_com();
    this.getCategory_com();
  },
  methods: {
    getCategory_com() {
      getCat({ pageSize: 999 }).then(res => {
        if (res.code === 200) {
          this.categories = res.data;
        }
      });
    },
    getCom_com() {
      getCommodity().then(res => {
        if (res.code === 200) {
          this.tableData = res.data;
        }
      });
    },
    handleAddAvatarSuccess(res, file) {
      this.formData.covers.push(`${res.originalname}`);
    },
    handleAvatarSuccess(index, res, file) {
      console.log(index, res, file);
      this.formData.covers[index] = `${res.originalname}`;
    },
    editRow(row) {
      this.isAdd = false;
      this.dialogVisible = true;
      this.editRowData = row;
      this.formData = {
        ...row,
        covers: row.covers.map(item => this.$getImageUrl(item))
      };
    },
    submitCommonRow() {
      console.log(this.formData);
      console.log(this.editRowData);
      if (this.isAdd) {
        addCommodities(this.formData).then(res => {
          this.dialogVisible = false;
          if (res.code === 200) {
            this.getCom_com();
            Message({ type: "success", message: "新增成功" });
          }
        });
      } else {
        editCommodities({ ...this.formData, id: this.editRowData._id }).then(
          res => {
            this.dialogVisible = false;
            if (res.code === 200) {
              this.getCom_com();
              Message({ type: "success", message: "修改成功" });
            }
          }
        );
      }
    },
    deleteRow(row) {
      deleteCommodities({ id: row._id }).then(res => {
        if (res.code === 200) {
          this.getCom_com();
          Message({ type: "success", message: "删除成功" });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.category {
  padding: 30px;
  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader {
    width: 120px;
    height: 120px;
    margin-bottom: 15px;
    margin-right: 15px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
}
</style>
